/*
 * This file is part of Euphrat.
 *
 * Copyright © 2012 Bart Verhoeven
 *
 * Euphrat is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Euphrat is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Euphrat. If not, see <http://www.gnu.org/licenses/>.
 */
package org.euphrat.server.service.login;

import org.euphrat.client.service.login.LoginService;
import org.euphrat.client.service.login.LoginContext;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * Server-side implementation of the login service that delegates authentication
 * to the Google Account Service.
 *
 * @author Bart Verhoeven
 */
public class LoginServiceImpl extends RemoteServiceServlet
implements LoginService {

  /**
   * <p>This implementation authenticates the user using his Google account. It
   * contacts the Google Account Service to see if the user is logged in with
   * his Google account credentials.</p>
   *
   * <p>If the user is logged in, his user name and email address are enclosed
   * inside the context. In addition, a URL is provided that redirects the user
   * to Google to log out.</p>
   *
   * <p>If the user is not logged in, an authentication URL is provided
   * that redirects the user to Google to log in.</p>
   *
   * <p><strong>Note:</strong> By no means does this service have access to your
   * Google account credentials. For more information on this service, see
   * <a href>https://developers.google.com/appengine/docs/java/users/</a>.</p>
   */
  @Override
  public LoginContext requestLogin(String requestUri) {
    UserService userService = UserServiceFactory.getUserService();
    User currentUser = userService.getCurrentUser();
    LoginContext context = new LoginContext();

    if (currentUser == null) {
      // The user is not logged in.
      String loginURL = userService.createLoginURL(requestUri);
      context.setLoginState(LoginContext.State.LOGGED_OUT);
      context.setLoginURL(loginURL);
    }
    else {
      // The user is logged in.
      boolean isAdmin = userService.isUserAdmin();
      String logoutURL = userService.createLogoutURL(requestUri);
      context.setLoginState(LoginContext.State.LOGGED_IN);
      context.setNickname(currentUser.getNickname());
      context.setAdmin(isAdmin);
      context.setEmailAddress(currentUser.getEmail());
      context.setLogoutURL(logoutURL);
    }

    return context;
  }
}
